package com.tanhua.server.service;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.constant.Constants;
import com.tanhua.dubbo.api.db.UserApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MessageService {

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;


    /**
     * 聊天信息中，显示用户信息
     * @param huanxinId
     * @return
     */
    public UserInfoVo findUserInfoByHuanxinId(String huanxinId) {
        User user = userApi.findByHuanXinUser(huanxinId);
        UserInfo userInfo = userInfoApi.findById(user.getId());
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, vo);
        //年龄转成字符串
        vo.setAge(userInfo.getAge().toString());
        return vo;
    }

    /**
     * 添加联系人
     * @param paramMap
     */
    public void addContacts(Map<String, Integer> paramMap) {
        Integer userId = paramMap.get("userId");
        //1. 调用api添加好友
        friendApi.makeFriends(UserHolder.getUserId(), userId.longValue());
        //2. 在环信注册为好友
        huanXinTemplate.addContact(UserHolder.getUser().getHxUser(), Constants.HX_USER_PREFIX + userId);
    }

    /**
     * 联系人列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult contactList(Long page, Long pagesize) {
        // 1. 分页查询登录用户的好友列表
        PageResult pageResult = friendApi.findPageByUserId(page,pagesize, UserHolder.getUserId());
        List<Friend> friendList = pageResult.getItems();
        List<ContactVo> voList = new ArrayList<>();
        // 2. 获取好友的ids
        if(CollectionUtil.isNotEmpty(friendList)) {
            List<Long> userIds = friendList.stream().map(Friend::getFriendId).collect(Collectors.toList());
            // 3. 查询好友的详情
            List<UserInfo> userInfoList = userInfoApi.findByBatchIds(userIds);
            // 4. 转成vo
            voList = userInfoList.stream().map(u -> ContactVo.init(u)).collect(Collectors.toList());
        }
        pageResult.setItems(voList);
        // 5. 返回
        return pageResult;
    }
}
